from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse

from myadmin import models
from django.contrib.auth.hashers import make_password, check_password


# Create your views here.

# 前台首页
def index(request):
    # 获取所有的一级分类
    data=models.Cates.objects.filter(pid=0)

    # 获取当前一级分类下的二级分类
    for x in data:
        x.sub=models.Cates.objects.filter(pid=x.id)
    context={'data':data}
    return render(request,'myhome/index.html',context)



def goodslist(request):
    #接收id
    cid=request.GET.get('cid')
    # 获取当前二级分类的对象
    ob=models.Cates.objects.get(id=cid)

    #获取排序方式
    ob.goodslist=models.Goods.objects.filter(cateid=ob).order_by(request.GET.get('orderby','id'))
    # 分配数据
    context={'data':ob}

    # 加载模板
    return render(request,'myhome/list.html',context)

def goodsinfo(request):
    # 接受商品id
    gid=request.GET.get('gid')

    # 根据商品id获取对象
    ob=models.Goods.objects.get(id=gid)
    # 分配数据
    context={'data':ob}
    # 加载模板
    return render(request,'myhome/info.html',context)



# 加入购物车
def cartadd(request):
    goods=models.Goods.objects.get(id=request.GET.get('gid'))
    user=models.Users.objects.get(id=request.session['VipUser']['uid'])
    num=int(request.GET.get('num'))

    # 检查当前的商品是否已经存在购物车
    res=models.Cart.objects.filter(goodsid=goods).filter(uid=user)

    if res.count():
        #已存在,更新数量
        for v in res:
            v.num+=num
            v.save()
    else:
        # 添加到数据库
        ob=models.Cart(goodsid=goods,uid=user,num=num)
        ob.save()

    return JsonResponse({'error':0,'msg':'加入购物成功'})










def login(request):
    nextpath=request.GET.get('nextpath','/')
    args=eval(request.GET.get('args','{}'))
    a=''
    for k,v in args.items():
        a+='&'+k+'='+v
    nexturl=nextpath+'?'+a


    if request.method=='GET':
        return render(request,'myhome/login.html')
    else:
        try:
            # 先根据手机号获取用户
            ob=models.Users.objects.get(phone=request.POST['phone'])
            # 在对比密码是否正确
            res=check_password(request.POST['password'],ob.password)
            if res:
                # 用户名和密码都正确
                # 在session中存入登录凭证
                request.session['VipUser']={'username':ob.username,'phone':ob.phone,'uid':ob.id,'pic_url':ob.pic_url}
                # 跳转到首页
                return HttpResponse('<script>alert("登录成功");location.href="'+nexturl+'"</script>')
            else:
                #密码错误
                pass
        except:
            #用户名不存在
            pass
        return HttpResponse('<script>alert("用户名或密码错误");location.href="'+reverse('myhome_login')+'"</script>')




def logout(request):
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录");location.href="/"</script>')

def register(request):
    if request.method == 'GET':
        return render(request, 'myhome/register.html')
    else:
        # try:
            # 验证手机号和验证码是否和session中一致
            if request.POST['phone'] != request.session['msgcode']['phone']:
                print(request.POST['phone'], "....." ,request.session['msgcode']['phone'])
                return HttpResponse('<script>alert("注册失败,手机号不正确");location.href="' + reverse('myhome_register') + '"</script>')
            if request.POST['code'] != request.session['msgcode']['code']:
                print(request.POST['code'], ".....", request.session['msgcode']['code'])
                return HttpResponse('<script>alert("注册失败,验证码不正确");location.href="' + reverse('myhome_register') + '"</script>')

            # 密码加密
            password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
            # 生成随机的用户名
            username = 'user' + str(request.POST['phone'])
            data = {'username': username, 'phone': request.POST['phone'], 'password': password}

            # 执行注册
            ob = models.Users(**data)
            ob.save()
            # 跳转登录页面
            return HttpResponse('<script>alert("注册成功.请登录");location.href="' + reverse('myhome_login') + '"</script>')
        # except:
            return HttpResponse('<script>alert("注册失败");location.href="' + reverse('myhome_register') + '"</script>')


def checkphone(request):
    # 接收手机号
    phone=request.GET.get('phone')
    # 到数据库查询
    num=models.Users.objects.filter(phone=phone).count()
    if num:
        return JsonResponse({'error':1,'msg':'手机号码已存在'})
    else:
        return JsonResponse({'error':0,'msg':'手机号码不存在'})

def sendmsg(request):
    # 接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    # 账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    # 注意事项：
    # （1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    # （2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    # （3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；

    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    # 用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account = "C04988412"
    # 密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "ca70bbd0206045c57873b014d5e9891f"
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000, 99999))
    print(code)
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    print({'phone':mobile,'code':code})
    # text = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'}
    # req = urllib.request.urlopen(
    #     url='http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data=urllib.parse.urlencode(data).encode('utf-8')
    # )
    # content = req.read()
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')






